import matplotlib.pyplot as plt
import numpy as np
import re

def plot_polygon(ax, vertices, show_points=True):
    if len(vertices) < 3:
        raise ValueError("多边形至少需要三个顶点")
    
    # 提取 x 和 y 坐标
    x_coords = [vertex[0] for vertex in vertices]
    y_coords = [vertex[1] for vertex in vertices]
    
    # 闭合多边形（将第一个点添加到末尾）
    x_coords.append(x_coords[0])
    y_coords.append(y_coords[0])

    
    # 绘制多边形
    ax.plot(x_coords, y_coords, 'b-', linewidth=1)
    
    # 如果需要，显示顶点
    if show_points:
        ax.plot(x_coords[:-1], y_coords[:-1], 'ro', markersize=2)
        # 添加顶点标签
        # for i, (x, y) in enumerate(zip(x_coords[:-1], y_coords[:-1])):
        #     ax.annotate(f'({x}, {y})', (x+0.1, y+0.1), fontsize=12)
    

def to_xy(sy_str):
    x, y = sy_str.split(',')
    return float(x), float(y)

if __name__ == "__main__":
    FILE = 'build/polygon_vec.txt'
    
    with open(FILE, 'r') as fd:
        data = fd.readlines()
    
    polygon_list = []
    for line in data:
        result = re.findall(r'\((.*?)\)', line) 
        point_list = []
        for point_index, xy_str in enumerate(result):
            x, y = to_xy(xy_str)
            point_list.append((x, y))
        polygon_list.append(point_list)

    # 绘制多边形
    fig, ax = plt.subplots()
    for polygon in polygon_list:
        plot_polygon(ax, polygon)    
    
    ax.set_aspect(1.0)
    ax.grid(True, which='both', linestyle='--', linewidth=0.5)
    ax.set_xticks(np.arange(0, 80+1, 10.0))  # x轴刻度步长5
    ax.set_yticks(np.arange(0, 100+1, 10.0))  # y轴刻度步长5
    
    plt.title("OBS_Polygon")
    plt.savefig('res/polygon.jpg')
    plt.show()